import { EventService } from 'src/app/shared/service/event.service';
import { Component, OnInit, Input } from "@angular/core";
import { FormGroup, FormControl, Validators } from '@angular/forms';

import { ModalController } from "@ionic/angular";

import { AppGlobalService } from "src/app/shared/service/app-global.service";
import { HttpService } from "src/app/shared/service/http.service";

@Component({
  selector: "app-remarks-content",
  templateUrl: "./remarks-content.component.html",
  styleUrls: ["./remarks-content.component.scss"]
})
export class RemarksContentComponent implements OnInit {
  openRemarks = false;
  remarksText = "";
  @Input() tagData: any;
  @Input() type: string;
  @Input() pageSize: number;
  @Input() item: any;
  @Input() textarea: any;
  openRemarksList = false;
  formGroup: FormGroup = new FormGroup({});
  allLabel: any = {};
  constructor(
    private appGlobalService: AppGlobalService,
    private httpService: HttpService,
    public modalController: ModalController,
    private eventService: EventService
  ) { }

  ngOnInit() {
    console.log(this.tagData);
    if (this.item && this.item.htmlObj) {
      this.buildForm();
    }
    if (this.item.formData.textarea.disable && this.item.formData.textarea.value){
      this.remarksText = this.item.formData.textarea.value;
    }
    if (this.textarea) {
      console.log(this.textarea);

      this.eventService.eventEmit.on('textareaSubmitDismiss', res => {
        this.modalController.dismiss();
      });
    }
  }

  textareaSubmit() {
    if (this.textarea.value.length < 1 || (this.textarea.value.length < this.textarea.minLength)) {
      this.appGlobalService.showToast("请填至少" + this.textarea.minLength + '个字', 1500, "top");
      return;
    }
    this.modalController.dismiss({ value: this.textarea.value });
  }
  /**
   * 提交备注
   */
  submitRemarks() {
    if (this.remarksText === "" || this.remarksText.trim() === "") {
      this.appGlobalService.showToast("请填写备注", 1000, "top");
      return;
    }
    const contentArray = this.item.formData.button
      .submit.content;
    contentArray.remark_text = this.remarksText;
    const params = {
      content: contentArray,
      id: this.item.formData.button.submit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {
      if (res.success) {
        this.openRemarks = false;
        this.modalController.dismiss({ dismissed: true });
        this.remarksText = "";
        // 根据页面配置size判断
        if (this.tagData) {
          if (this.tagData.data.data.length >= this.pageSize) {
            this.tagData.data.data.pop();
            this.tagData.data.data = [res.data, ...this.tagData.data.data];
          } else if (this.tagData.data.data.length > 0) {
            this.tagData.data.data = [res.data, ...this.tagData.data.data];
          } else {
            this.tagData.data.data.push(res.data);
          }
          // this.tagData.data.data.push(res.data);

        }
        this.appGlobalService.showToast(res.message, 1000, "middle");
      } else {
        this.appGlobalService.showToast(res.message, 1000, "bottom");
      }
    });
  }

  // 添加表单控件
  buildForm(): void {
    // tslint:disable-next-line:prefer-for-of
    for (let i = 0; i < this.item.htmlObj.length; i++) {
      const formItem = this.item.htmlObj[i];
      this.addFormCtrl(formItem);
    }
  }
  addFormCtrl(formItem) {
    const that = this;
    if (formItem.formKey && formItem.formKey.length > 0) {

      this.addFormControl(formItem);
    }
  }
  addFormControl(formItem) {

    const that = this;
    if (formItem.formKey && formItem.formKey.length > 1 && !this.formGroup.controls[formItem.formKey]) {
      this.formGroup.addControl(formItem.formKey, new FormControl(formItem.value, that.validators(formItem)));
    }
    if (formItem.rules && formItem.rules.length > 0) {
      const message: any = {};
      formItem.rules.forEach(rule => {
        // 将key 转小写
        message[rule.name.toLowerCase()] = rule.message;
      });
      message.label = formItem.label;
      this.allLabel[formItem.formKey] = message;
    }
  }
  // 数据校验
  validators(item) {
    const validators = [];
    if (item.rules && item.rules.length) {
      item.rules.forEach(rule => {
        if (rule.name === 'required' && rule.value === 'true') {
          validators.push(Validators.required);
        } else if (rule.name === 'minLength') {
          validators.push(Validators.minLength(Number(rule.value)));
        } else if (rule.name === 'maxLength') {
          validators.push(Validators.maxLength(Number(rule.value)));
        } else if (rule.name === 'min') {
          validators.push(Validators.min(Number(rule.value)));
        } else if (rule.name === 'max') {
          validators.push(Validators.max(Number(rule.value)));
        } else if (rule.name === 'pattern') {
          validators.push(Validators.pattern(rule.value));
        }
      });
    }
    return validators;
  }
  submit() {
    this.item.disabled = false;
    const formKeyObj: any = {};
    if (this.formGroup.valid) {
      // console.log(this.formGroup.value);
      const params = this.formGroup.value;
      // tslint:disable-next-line:forin
      for (const prop in params) {
        if (Array.isArray(params[prop])) {
          params[prop] = params[prop].join(',');
        }
        // 删除无效值
        if (prop === '') {
          // delete params[prop];
        }
        if (prop.indexOf('cus_') > -1) {
          const p = prop.substring(4, prop.length - 1);
          formKeyObj[p] = formKeyObj[p] ? formKeyObj[p] : [];
          formKeyObj[p].push(params[prop]);
          this.formGroup.removeControl(prop);
          delete params[prop];
        }
      }
      // 组合表单值
      for (const key in formKeyObj) {
        if (Array.isArray(formKeyObj[key])) {
          const value = formKeyObj[key].join(',');
          this.formGroup.patchValue({ [key]: value });
        }
      }
      this.modalController.dismiss({ dismissed: true });
      Object.keys(params).forEach(key => {
        this.item.submit.content[key] = params[key];
      });
      this.item.submit.sessionId = localStorage.getItem('sessionId');
      this.httpService.post('application/submit', this.item.submit, res => {
        this.appGlobalService.showToast(res.message, 2000, 'middle');
        this.httpService.reloadCurrentPage();
        setTimeout(() => {
          localStorage.setItem('needRefresh', 'true');
        }, 2000);
        this.item.disabled = false;
      });

    } else {
      this.getErrors(this.formGroup);
      this.item.disabled = false;
    }
  }

  getErrors(form) {
    const errs = [];
    for (const name in form.controls) {
      // eg: controls[name] = phone
      if (form.controls[name].errors) {
        errs.push({ key: [name], err: form.controls[name].errors });
      }
    }
    if (errs.length) {
      const errItem = errs[0];

      const firstErrMsgKey = Object.keys(errItem.err)[0];
      console.log(errItem.key, '校验的字段名');
      const messageObj = this.allLabel[errItem.key];
      let showMessage = messageObj[firstErrMsgKey];
      if (errItem.err.rangeError !== undefined) {
        const label = messageObj.label.slice(-2);
        showMessage = `${messageObj.label}不得小于/等于最小${label}`;
      }
      this.appGlobalService.showToast(showMessage, 3000, 'top');

    }
  }
  cancelClick(e){
    e.stopPropagation();
  }
  dismissClick(){
    this.modalController.dismiss();

  }
}
